package org.security.oauth2.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.security.oauth2.domain.RoleMapper;
import org.security.oauth2.domain.UserBaseMapper;
import org.security.oauth2.model.Role;
import org.security.oauth2.model.UserBase;
import org.security.oauth2.model.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService{

	/**
	 * 用户Mapper
	 */
	@Autowired
	private UserBaseMapper userMapper;
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private SqlSession sqlSession;
	
	private static Logger log = Logger.getLogger(UserDetailsServiceImpl.class);
	
	/**
	 * 取得用户情报
	 * 
	 * @param username 用户名
	 * @return 用户情况
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserBase result = userMapper.selectByPrimaryKey(username);
		return new UserDetailsImpl(result, true, true, true, true, getAuthorities(result));
	}
	
    /**
     * 获得访问角色权限
     *
     * @param authorities
     * @return
     */
    public Collection<GrantedAuthority> getAuthorities(UserBase userInfo) {
        log.debug("获取用户权限");

        List<GrantedAuthority> authList = new ArrayList<>();
        
        List<Role> roleList = new ArrayList<>();
        
        //List<Role> roleList = roleMapper.roleList(userInfo.getUserName());
        roleList = sqlSession.selectList("authorityInfo.getRole", userInfo);

        // 所有的用户默认拥有ROLE_USER权限
        authList.add(new SimpleGrantedAuthority("ROLE_USER"));
        // 获取当前用户权限
        for (int i = 0; i <roleList.size(); i++) {
            if (roleList.get(i).toString()!=null){
                authList.add(new SimpleGrantedAuthority(roleList.get(i).getRoleName()));
            }
        }

        return authList;
    }

}
